package servlet;

import entity.Student;
import service.StudentService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "StudentOpServlet",urlPatterns = "/students")
public class StudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String index = request.getParameter("index");
        String perpage = request.getParameter("perpage");
        System.out.println("index :" +index);
        System.out.println("perpage:"+perpage);

        int in = Integer.parseInt(index != null?index:"0");
        int per = Integer.parseInt(perpage != null?perpage:"3");

        StudentService studentService = new StudentService();
        //查找学生
        String si = request.getParameter("sid");
        if ((!"".equals(si) && si != null)) {

            List<Student> students = studentService.findStudentByIdService(si);
            request.setAttribute("studentscount", (long) students.size());
            request.setAttribute("students", students);
            request.setAttribute("next", 0);
            request.setAttribute("previous", 0);
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("student.jsp");
            requestDispatcher.forward(request, response);
            return;
        }
        //非查找学生显示
        List<Student> students = studentService.getStudentListService(in*per, per);
        long studentsCount = studentService.getStudentsCountService();
        for (Student st:students){
            System.out.println(st);
        }
        request.setAttribute("students",students);
        request.setAttribute("studentscount",studentsCount);

        int pageindex = in+1;
        int pagecount = (int) Math.ceil(studentsCount / 3.0);

        int previous = 0;
        int next=0;

        if (pagecount > pageindex) {
            previous = in >= 1 ? in - 1 : 0;
            next = pageindex;

        }

        if (pagecount == pageindex) {
            previous = in > 1 ? in - 1 : 0;
            next = in;

        }

        request.setAttribute("previous",previous);
        request.setAttribute("next",next);
        System.out.println("previous"+previous);
        System.out.println("next:"+next);
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("student.jsp");
        requestDispatcher.forward(request,response);

    }
}

